package com.ruoyi.staffing.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.staffing.domain.HrCandidate;
import com.ruoyi.staffing.domain.HrCandidateExperience;
import com.ruoyi.staffing.domain.HrCandidateFamily;
import com.ruoyi.staffing.mapper.HrCandidateMapper;
import com.ruoyi.staffing.service.IHrCandidateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * HR-候选人(求职登记)主Service业务层处理
 *
 * 说明：
 * 1) 新增/修改候选人时，支持同时维护子表（经历/家庭成员）：
 *    - 新增：插入主表后，回填主键到子表的 candidateId，再批量插入子表。
 *    - 修改：更新主表后，按 candidateId 先物理删除原子表记录，再批量插入最新的子表记录。
 * 2) 所有“主 + 子”写操作放入同一事务中，确保一致性。
 *
 * @author hango
 * @date 2025-10-13
 */
@Service
public class HrCandidateServiceImpl implements IHrCandidateService
{
    @Autowired
    private HrCandidateMapper hrCandidateMapper;

    /**
     * 查询HR-候选人(求职登记)主
     *
     * @param id HR-候选人(求职登记)主主键
     * @return HR-候选人(求职登记)主
     */
    @Override
    public HrCandidate selectHrCandidateById(Long id)
    {
        HrCandidate cand = hrCandidateMapper.selectHrCandidateById(id);
        if (cand != null) {
            // 组装子表数据，便于前端一次拿全
            cand.setExperiences(selectExperienceByCandidateId(id));
            cand.setFamilies(selectFamilyByCandidateId(id));
        }
        return cand;
    }

    /**
     * 查询HR-候选人(求职登记)主列表
     *
     * @param hrCandidate HR-候选人(求职登记)主
     * @return HR-候选人(求职登记)主集合
     */
    @Override
    public List<HrCandidate> selectHrCandidateList(HrCandidate hrCandidate)
    {
        return hrCandidateMapper.selectHrCandidateList(hrCandidate);
    }

    /**
     * 新增HR-候选人(求职登记)主（含子表）
     *
     * @param hrCandidate HR-候选人(求职登记)主（可携带 experiences / families）
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertHrCandidate(HrCandidate hrCandidate)
    {
        hrCandidate.setCreateTime(DateUtils.getNowDate());
        int rows = hrCandidateMapper.insertHrCandidate(hrCandidate);
        Long candidateId = hrCandidate.getId();

        List<HrCandidateExperience> expList = normalizeExpList(hrCandidate.getExperiences(), candidateId);
        if (!expList.isEmpty()) {
            hrCandidateMapper.batchInsertExperience(expList);
        }

        List<HrCandidateFamily> famList = normalizeFamList(hrCandidate.getFamilies(), candidateId);
        if (!famList.isEmpty()) {
            hrCandidateMapper.batchInsertFamily(famList);
        }

        return rows;
    }

    /**
     * 修改HR-候选人(求职登记)主（含子表“先删后插”）
     *
     * @param hrCandidate HR-候选人(求职登记)主（可携带 experiences / families）
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateHrCandidate(HrCandidate hrCandidate)
    {
        hrCandidate.setUpdateTime(DateUtils.getNowDate());
        int rows = hrCandidateMapper.updateHrCandidate(hrCandidate);
        Long candidateId = hrCandidate.getId();

        // 统一用“先删后插”的方式覆盖子表
        hrCandidateMapper.deleteExperienceByCandidateId(candidateId);
        hrCandidateMapper.deleteFamilyByCandidateId(candidateId);

        List<HrCandidateExperience> expList = normalizeExpList(hrCandidate.getExperiences(), candidateId);
        if (!expList.isEmpty()) {
            hrCandidateMapper.batchInsertExperience(expList);
        }

        List<HrCandidateFamily> famList = normalizeFamList(hrCandidate.getFamilies(), candidateId);
        if (!famList.isEmpty()) {
            hrCandidateMapper.batchInsertFamily(famList);
        }

        return rows;
    }

    /**
     * 批量删除HR-候选人(求职登记)主（含子表）
     *
     * @param ids 需要删除的HR-候选人(求职登记)主主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteHrCandidateByIds(Long[] ids)
    {
        // 先删子表，再删主表
        if (ids != null) {
            for (Long id : ids) {
                if (id != null) {
                    hrCandidateMapper.deleteExperienceByCandidateId(id);
                    hrCandidateMapper.deleteFamilyByCandidateId(id);
                }
            }
        }
        return hrCandidateMapper.deleteHrCandidateByIds(ids);
    }

    /**
     * 删除HR-候选人(求职登记)主信息（含子表）
     *
     * @param id HR-候选人(求职登记)主主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteHrCandidateById(Long id)
    {
        // 先删子表，再删主表
        hrCandidateMapper.deleteExperienceByCandidateId(id);
        hrCandidateMapper.deleteFamilyByCandidateId(id);
        return hrCandidateMapper.deleteHrCandidateById(id);
    }

    /* ======================= 子表：经历 ======================= */

    /**
     * 按候选人ID查询工作/教育经历列表
     *
     * @param candidateId 候选人ID
     * @return 经历集合（含 work/edu）
     */
    @Override
    public List<HrCandidateExperience> selectExperienceByCandidateId(Long candidateId)
    {
        return hrCandidateMapper.selectExperienceByCandidateId(candidateId);
    }

    /**
     * 按候选人ID删除所有经历（物理删）
     *
     * @param candidateId 候选人ID
     * @return 影响行数
     */
    @Override
    public int deleteExperienceByCandidateId(Long candidateId)
    {
        return hrCandidateMapper.deleteExperienceByCandidateId(candidateId);
    }

    /**
     * 批量新增经历
     *
     * @param list 经历集合
     * @return 影响行数
     */
    @Override
    public int batchInsertExperience(List<HrCandidateExperience> list)
    {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        return hrCandidateMapper.batchInsertExperience(list);
    }

    /* ======================= 子表：家庭成员 ======================= */

    /**
     * 按候选人ID查询家庭成员列表
     *
     * @param candidateId 候选人ID
     * @return 家庭成员集合
     */
    @Override
    public List<HrCandidateFamily> selectFamilyByCandidateId(Long candidateId)
    {
        return hrCandidateMapper.selectFamilyByCandidateId(candidateId);
    }

    /**
     * 按候选人ID删除所有家庭成员（物理删）
     *
     * @param candidateId 候选人ID
     * @return 影响行数
     */
    @Override
    public int deleteFamilyByCandidateId(Long candidateId)
    {
        return hrCandidateMapper.deleteFamilyByCandidateId(candidateId);
    }

    /**
     * 批量新增家庭成员
     *
     * @param list 家庭成员集合
     * @return 影响行数
     */
    @Override
    public int batchInsertFamily(List<HrCandidateFamily> list)
    {
        if (list == null || list.isEmpty()) {
            return 0;
        }
        return hrCandidateMapper.batchInsertFamily(list);
    }


    /** 规范化经历列表：填充 candidateId、默认时间字段等 */
    private List<HrCandidateExperience> normalizeExpList(List<HrCandidateExperience> src, Long candidateId)
    {
        List<HrCandidateExperience> list = new ArrayList<>();
        if (src == null) return list;
        for (HrCandidateExperience e : src)
        {
            if (e == null) continue;
            e.setId(null); // 走自增
            e.setCandidateId(candidateId);
            // create_time / update_time 由数据库默认值处理；如需手动可设置：
            e.setCreateTime(DateUtils.getNowDate());
            e.setUpdateTime(DateUtils.getNowDate());
            list.add(e);
        }
        return list;
    }

    /** 规范化家庭成员列表：填充 candidateId、默认时间字段等 */
    private List<HrCandidateFamily> normalizeFamList(List<HrCandidateFamily> src, Long candidateId)
    {
        List<HrCandidateFamily> list = new ArrayList<>();
        if (src == null) return list;
        for (HrCandidateFamily f : src)
        {
            if (f == null) continue;
            f.setId(null); // 走自增
            f.setCandidateId(candidateId);
            // f.setCreateTime(DateUtils.getNowDate());
            // f.setUpdateTime(DateUtils.getNowDate());
            list.add(f);
        }
        return list;
    }
}
